package com.self.liu.client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

public class ZkClientManager {

    private static ZooKeeper zk = null;

    private static String zkips = "192.168.59.128:2181,192.168.59.129:2181,192.168.59.130:2181";

    private static String path = "/thrift/baseservice";

    public static String url = null;

    private ZkClientManager() {
    }

    private static String getUrl() {
        try {
            if (null == zk) {
                zk = new ZooKeeper(zkips, 120, new Watcher() {
                    @Override
                    public void process(WatchedEvent event) {
                        System.out.println("Zookeeper 已连接。");
                    }

                });
            }
            List<String> serverList = zk.getChildren(path, new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    url = getUrl();
                }

            });
            System.out.println(serverList);
            Map<String, Integer> map = new HashMap<String, Integer>();
            for (String serverName : serverList) {
                map.put(serverName, 1);
            }
            return getRandomUrl(map);
        } catch (Exception e) {
            return null;
        }
    }

    public static int getPort() {
        if (url == null) {
            url = getUrl();
        }
        if (url != null) {
            return Integer.valueOf(url.split(":")[1]);
        } else {
            return 9999;
        }
    }

    public static String getIp() {
        if (url == null) {
            url = getUrl();
        }
        if (url != null) {
            return url.split(":")[0];
        } else {
            return null;
        }
    }

    public static void delUrl() {
        try {
            if (null == zk) {
                zk = new ZooKeeper(zkips, 1, new Watcher() {
                    @Override
                    public void process(WatchedEvent event) {
                        System.out.println("Zookeeper 已连接。");
                    }

                });
            }
            url = null;
            zk.delete(path + "/" + url, -1);
        } catch (Exception e) {
        }
    }

    private static String getRandomUrl(Map<String, Integer> map) {
        List<String> list = new ArrayList<String>();
        for (String key : map.keySet()) {
            int num = map.get(key);
            do {
                list.add(key);
                num--;
            } while (num > 0);
        }
        int index = (int) (Math.random() * list.size());
        return list.get(index);
    }
}